package com.dems.remote.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dems.core.util.PasswordUtil;
import com.dems.domain.sms.YifanSendReqVO;
import com.dems.domain.sms.YifanSendResVO;
import com.dems.remote.IYifanSmsProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 忆凡短信 发送客户端
 * account:帐号（短信平台提供）
 * password:密码（短信平台提供，需用MD5加密，32位，加密后字母全部为小写，例如： “123.com”
 * 加密后应该是“cbff36039c3d0212b3e34c23dcde1456”可以用此例子验证加密方法是否正确）
 * smsType:短信业务类型（短信平台提供）
 * mobile:手机号码（多个以英文逗号隔开）
 * content:接收短信内容
 */
@Slf4j
@Component
public class YifanSmsProxyImpl implements IYifanSmsProxy {

    private static final String account = "xianglong";

    private static final String password = "xl666@yf";

    public String contentTemplate = "【快信通】欢迎您登录快信通，验证码：VCODE。请不要把验证码泄露给其他人，如非本人操作，可不用理会！";

    /**
     * 短信发送Url
     */
    private static final String yifanSendPostUrl = "http://106.15.42.125:8001/webService/restSmsService/smsService/sendSmsByPost.json";

    @Autowired
    private RestTemplate restTemplate;


    @Override
    public String send(String phoneNo, String content) {
        YifanSendReqVO yifanSendReqVO = new YifanSendReqVO(account, PasswordUtil.md5Hex(password).toLowerCase());

        yifanSendReqVO.setMobile(phoneNo);
        yifanSendReqVO.setContent(content);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

        JSONObject paraJson = JSON.parseObject(JSON.toJSONString(yifanSendReqVO));

        paraJson.forEach((key, value) -> map.put(key, Collections.singletonList(Objects.toString(value, null))));

        HttpEntity<?> request = new HttpEntity<>(map, requestHeaders);
        String response = restTemplate.postForObject(yifanSendPostUrl, request, String.class);
        log.info("applyId={} 短信发送信息是{}", phoneNo, response);

        if (StringUtils.isEmpty(response)) {
            return null;
        }

        YifanSendResVO yifanSendResVO = JSON.parseObject(response, YifanSendResVO.class);
        return yifanSendResVO.getSmsId();
    }

    @Override
    public int sendBatch(List<String> phoneNoList, String content) {
        return 0;
    }
}
